import fs from 'fs'
let config = {}
export const createSkeleton = () => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    config = JSON.parse(data)
    skeleton('router')
    skeleton('store')
    skeleton('http')
  })
}

const skeleton = (type) => {
  // verify file is exist or not
  let content = ''
  let fileName = ''
  let folder = ''
  switch (type) {
    case 'router':
      content = routerContent()
      fileName = config.router.fileName
      folder = config.router.folder
      break
    case 'store':
      content = storeContent()
      fileName = config.store.fileName
      folder = config.store.folder
      break
    case 'http':
      content = httpContent()
      folder = config.http.folder
      fileName = config.http.fileName
      break
  }
  if (!fs.existsSync(`${folder}/${fileName}.ts`)) {
    // file is not exist
    if (!fs.existsSync(folder)) {
      fs.mkdirSync(folder, { recursive: true }, (err) => {
        if (err) throw err
      })
    }

    fs.writeFile(`${folder}/${fileName}.ts`, content, { flag: 'a' }, (err) => {
      if (err) {
        console.log(`========create skeleton ${type} faily======`)
        throw err
      } else {
        console.log(`==========create skeleton ${type} succeessfully==============`)
      }
    })
  }
}

const routerContent = () => {
  return `
import { createRouter, RouteRecordRaw, RouteLocationNormalized, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import { topRouter } from '@/vendors/topRouter'
import 'nprogress/css/nprogress.css' // 进度条样式
const home = {
  path: '/home',
  name: 'Home',
  component: () => import('@/components/layout/Home.vue'),
  meta: {
    title: '首页'
  }
}
const layout = [
{
  path: '/layout',
  component: () => import('@/components/layout/Layout.vue'),
  children: topRouter.concat(home)
},
{
  path: '/login',
  component: () => import('@/components/login/Login.vue'),
  meta:{
    title:'Login'
  }
}
]
NProgress.configure({ showSpinner: false })
const routes:Array<RouteRecordRaw> = layout

const router = createRouter({
  history: createWebHistory(),
  routes
})
router.beforeEach((next:RouteLocationNormalized, from:RouteLocationNormalized) => {
  NProgress.start()
  return true
})
router.afterEach((next, from) => {
  if (next.meta) {
    if (next.meta.title) {
      document.title = next.meta.title as string
    }
  }
  NProgress.done()
})
export default router
`
}

const storeContent = () => {
  return `
import { createStore } from 'vuex'
import { topStore } from '@/vendors/topStore'
const tokenModule = {
  state () {
    return {}
  },
  getters: {
    getAccessToken: (state:any) => ():string => {
      return localStorage.getItem('accessToken') as string
    }
  },
  mutations: {
    setAccessToken (state:any, accessToken: string) {
      localStorage.setItem('accessToken', accessToken)
    }
  },
  actions: {
    // token
    setAccessToken (context:any, accessToken:string) {
      return new Promise((resolve:any) => {
        context.commit('setAccessToken', accessToken)
        resolve()
      })
    }
  }
}
const storeModules = Object.assign({ tokenModule }, topStore)
const store = createStore({ modules: storeModules })
export default store
`
}

const httpContent = () => {
  const path = config.store.folder.replace(/..\//, '') === '' ? '' : '/' + config.store.folder.replace(/..\//, '')
  return `
import store from '@${path}store'
import axios from 'axios'
import qs from 'qs'
const https = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000

})
// 请求拦截器
https.interceptors.request.use(
  (config:any) => {
    if (config.url.indexOf('CDF') > -1 || config.url.indexOf('cdfgsanya') > -1) {
      config.baseURL = import.meta.env.VITE_APP_HNFD_API
    }
    // 添加请求头
    const accessToken = store.getters.getAccessToken()
    if (accessToken) {
      config.headers.Authorization = accessToken
    }
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
https.interceptors.response.use(
  (res) => {
    // console.log('successss')
    return res.data
  },
  (error) => {
    return Promise.reject(error)
  }
)

// POST
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function fetchPost (url: string, params: any) {
  return new Promise((resolve, reject) => {
    https
      .post(url, qs.stringify(params))
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}

// put
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function fetchPut (url: string, params: any) {
  if (store.getters.getBannedAllReq()) return // 禁止请求
  return new Promise((resolve, reject) => {
    https
      .put(url, qs.stringify(params))
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}

// patch
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function fetchPatch (url: string, params: any) {
  if (store.getters.getBannedAllReq()) return // 禁止请求
  return new Promise((resolve, reject) => {
    https
      .patch(url, qs.stringify(params))
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}

// Delete
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function fetchDel (url: string) {
  if (store.getters.getBannedAllReq()) return // 禁止请求
  return new Promise((resolve, reject) => {
    https
      .delete(url)
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}

// get
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function fetchGet (url: string, params:any = {}) {
  if (store.getters.getBannedAllReq()) return // 禁止请求
  return new Promise((resolve, reject) => {
    https
      .get(url, { params })
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
      .catch((error) => {
        reject(error)
      })
  })
}

// 超时重新请求
async function reRequest (promise:Promise<any>, callBack:Function) {
  let exit = false
  while (!exit) {
    const res = await promise
    if (res) {
      exit = true
    }
  }
}

/**
 * 验证auth是否还有效
 * @returns  false 否 true  是
 */
function validateToeknExpire () {
  const curUnixTime = Math.floor(Date.now() / 1000)
  const refreshAfter = store.getters.getTokenRefreshAfter()
  if (curUnixTime >= refreshAfter) {
    return false
  }
  return true
}

const http = {
  fetchGet,
  fetchPost,
  fetchDel,
  fetchPut,
  fetchPatch,
  reRequest,
  validateToeknExpire
}
export default http
`
}
